#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdio.h>
#include <cstdlib>

const int size = 4096;

void Usage(const std::string &s)
{
	std::cout << "\n\t" << s << " serverip serverport" << std::endl;
}

// int main(int argc, char *argv[])
// {
// 	if (argc != 3)
// 	{
// 		Usage(argv[0]);
// 		return 0;
// 	}
// 	struct sockaddr_in server;
// 	server.sin_port = htons(std::stoi(argv[2]));
// 	server.sin_family = AF_INET;
// 	std::string serverip = argv[1];
// 	inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
// 	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
// 	if (sockfd < 0)
// 	{
// 		perror("socket error");
// 		return 0;
// 	}
// 	int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
// 	if (n < 0)
// 	{
// 		perror("connect error");
// 		return 0;
// 	}
// 	char buffer[size];
// 	std::string msg;
// 	while (true)
// 	{
// 		std::cout << "please enter@ ";
// 		std::getline(std::cin, msg);
// 		write(sockfd, msg.c_str(), msg.size());
// 		int n = read(sockfd, buffer, size);
// 		if (n > 0)
// 		{
// 			buffer[n] = 0;
// 			std::cout << buffer << std::endl;
// 		}
// 	}
// 	return 0;
// }

int main(int argc, char *argv[])
{
	if (argc != 3)
	{
		Usage(argv[0]);
		return 0;
	}
	struct sockaddr_in server;
	server.sin_port = htons(std::stoi(argv[2]));
	server.sin_family = AF_INET;
	std::string serverip = argv[1];
	inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);
	while (true)
	{
		int sockfd = socket(AF_INET, SOCK_STREAM, 0);
		if (sockfd < 0)
		{
			perror("socket error");
			return 0;
		}
		bool reconnet = false;
		int cnt = 5;
		do
		{
			int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
			if (n < 0)
			{
				std::cout << "connect error , reconnect:" << cnt << std::endl;
				cnt--;
				reconnet = true;
				sleep(2);
			}
			else
			{
				break;
			}
		} while (reconnet && cnt);
		if(cnt == 0){
			std::cout << "usersoff online" << std::endl;
			break;
		}
		char buffer[size];
		std::string msg;
		std::cout << "please enter@ ";
		std::getline(std::cin, msg);
		write(sockfd, msg.c_str(), msg.size());
		int n = read(sockfd, buffer, size);
		if (n > 0)
		{
			buffer[n] = 0;
			std::cout << buffer << std::endl;
		}
		close(sockfd);
	}
	return 0;
}